package com.tiance.domainservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.tiance.dal.dao.SignInDAO;
import com.tiance.dal.dataobject.SignInDO;
import com.tiance.domainservice.assemble.DOAssemble;
import com.tiance.domainservice.domain.IntegrationDomain;
import com.tiance.domainservice.domain.SignInDomain;
import com.tiance.domainservice.service.IntegrationService;
import com.tiance.domainservice.service.SignInService;
import com.tiance.enums.*;
import com.tiance.exception.BusinessException;
import com.tiance.page.QueryPage;
import com.tiance.utils.DateUtils;
import com.tiance.utils.MapUtil;
import com.tiance.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/2/14
 *
 * Description：
 *
 * Modification History:
 *
 */
@Service
public class SignInServiceImpl implements SignInService {


    protected static final Logger logger = LoggerFactory.getLogger(SignInServiceImpl.class);

    @Resource
    private SignInDAO signInDAO;

    @Autowired
    private IntegrationService integrationService;

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public SignInDO addSignIn(SignInDomain signInDomain) throws Exception {
        SignInDO signInDO= DOAssemble.assembleSignInDO(signInDomain);
        //系统默认为会员每日签到
        int signCount;
        Map<String,Object> paramMap= MapUtil.params2Map(new Object[]{ "memberId", StringUtil.trimNull(signInDomain.getMemberId())});
        if(SignInTypeEnum.DAILY_SIGN_IN.getCode().equals(signInDomain.getSignInType())){
            paramMap.put("startTime",DateUtils.getOneDayStart(new Date(),0));
            paramMap.put("endTime",new Date());
            logger.info("开始会员是否已签到，参数:{}", JSON.toJSONString(paramMap));
            signCount =signInDAO.querySignInCount(paramMap);
            logger.info("结束查询签到总数，返回总数:{}", signCount);
            signInDO.setEntityId(signInDomain.getMemberId());
            signInDO.setEntityType(EntityTypeEnum.MEMBER.getCode());
        }else{
            paramMap.put("entityId",signInDomain.getEntityId());
            paramMap.put("entityType",signInDomain.getEntityType());
            logger.info("开始会员是否已签到，参数:{}", JSON.toJSONString(paramMap));
            signCount =signInDAO.querySignInCount(paramMap);
            logger.info("结束查询签到总数，返回总数:{}", signCount);
        }
        if(signCount>0){
            throw new BusinessException("请勿重复签到！");
        }

        logger.info("开始插入签到数据，参数:{}", JSON.toJSONString(signInDO));
        Long count=signInDAO.insert(signInDO);
        logger.info("结束插入签到，是否插入成功:{}", count>0?true:false);
        if(count<1){
            throw new BusinessException("插入失败");
        }
        IntegrationDomain integrationDomain=new IntegrationDomain();
        integrationDomain.setIntegrationType(IntegrationTypeEnum.INTEGRATION.getCode());
        integrationDomain.setMemberId(signInDomain.getMemberId());
        integrationDomain.setBelongType(IntegrationBelongTypeEnum.MEMBER.getCode());
        if(SignInTypeEnum.DAILY_SIGN_IN.getCode().equals(signInDomain.getSignInType())){
            integrationDomain.setIntegrationRuleCode(IntegrationRuleCodeEnum.REGULAR_MEMBER_SIGN_IN_ON_LINE);
            integrationService.addIntegration(false,integrationDomain);

        }else if(SignInTypeEnum.ACTIVITY_SIGN_IN.getCode().equals(signInDomain.getSignInType())){
           // integrationDomain.setIntegrationRuleCode(IntegrationRuleCodeEnum.REGULAR_MEMBER_SIGN_IN_ON_LINE);
            integrationService.addIntegration(false,integrationDomain);
        }else if(SignInTypeEnum.CONFERENCE_CENTER_SIGN_IN.getCode().equals(signInDomain.getSignInType())){

        }
        return signInDO;
    }

    @Override
    public List<SignInDO> querySignInList(SignInDomain domain) {

        Map<String,Object> paramMap= MapUtil.params2Map(new Object[]{ "memberId", domain.getMemberId()});
        logger.info("开始查询签到总数，参数:{}", JSON.toJSONString(paramMap));
        int count  =signInDAO.querySignInCount(paramMap);
        logger.info("结束查询签到总数，返回总数:{}", count);


        if(0==count){
            return new ArrayList();
        }

        QueryPage queryPage = domain.getQueryPage();
        queryPage.setTotalItem(count);
        paramMap.put("queryPage", queryPage);
        if (queryPage.getEndRow() == 0) {
            queryPage.setStartRow(queryPage.getPageFristItem());
            queryPage.setEndRow(queryPage.getPageLastItem());
        }


        logger.info("开始查询签到数据，参数:{}", JSON.toJSONString(paramMap));
        List<SignInDO> signInDOList =signInDAO.querySignInList(paramMap);
        logger.info("结束查询签到，查询结果:{}", JSON.toJSONString(signInDOList));
        return signInDOList;
    }

    @Override
    public String queryMemberSignStatus(Long memberId) {

        Map<String,Object> paramMap= MapUtil.params2Map(new Object[]{ "memberId", memberId},
                new Object[]{ "startTime", DateUtils.getOneDayStart(new Date(),0)},
                new Object[]{ "endTime", new Date()});

        logger.info("开始会员是否已签到，参数:{}", JSON.toJSONString(paramMap));
        int count  =signInDAO.querySignInCount(paramMap);
        logger.info("结束查询签到总数，返回总数:{}", count);

        return count>0? SignInStatusEnum.SIGN_IN.getCode():SignInStatusEnum.NOT_SIGN_IN.getCode();
    }
}
